package com.codejob.portal.web.action.algorithm;

import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.codejob.portal.entity.algorithm.Problem;
import com.codejob.portal.entity.user.Users;
import com.codejob.portal.services.impl.algorithm.ProblemManager;
import com.codejob.portal.services.intf.BusinessExcption;
import com.codejob.portal.web.BaseAction;
import com.codejob.portal.web.utils.Struts2Utils;
import com.codejob.portal.web.utils.Token;

@Namespace("/problem")
@Results({
		@Result(name = "index", location = "../index.jsp", type = "redirect"),
		@Result(name = "login", location = "/user/user!login.action", type = "redirect") })
public class ProblemAction extends BaseAction {

	private static final long serialVersionUID = 6973242004911223170L;

	private Problem problem; 
	
	private List<Problem> problemList;
	
	@Autowired
	ProblemManager problemManager;

	public String prepareStudy() {
		try {
			problemList=problemManager.getProblemList();
		} catch (BusinessExcption e) {
			e.printStackTrace();
		}
		
		return "studyInfo";
	}

	public String prepareCreate() {
		// if(!isManager()){
		// return "login";
		// }
		return "createProblem";
	}

	@Token
	public String createProblem() {
		 if(!isManager()){
		 return "login";
		 }		
		try {
			Users user=(Users)Struts2Utils.getSession().getAttribute("user");
			problem.setType(problem.getSubType());
			List<Problem> p = null;
			if (problem.getType() > 0) {
				p = problemManager.findSubTypeMaxValueByType(problem.getSubType());

				if (!p.equals(null)) {	
					String ss = p.get(0)+"";
					if(ss!=null&&ss.length()>4){
						problem.setSubType(Integer.parseInt(ss)+1);
					}else{
						ss = problem.getSubType()+"0000";
						problem.setSubType(Integer.parseInt(ss)+1);
					}
				}
			}
			problem.setCreateDate(new Date());
			problem.setMenuCatalog(3);			
			problem.setUser(user);
			problemManager.createProblem(problem);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "createSuccess";
	}

	public Problem getProblem() {
		return problem;
	}

	public void setProblem(Problem problem) {
		this.problem = problem;
	}

	public List<Problem> getProblemList() {
		return problemList;
	}

	public void setProblemList(List<Problem> problemList) {
		this.problemList = problemList;
	}

}
